package com.google.rui.demos.apn;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;

/**
 * Apn�࣬�ṩ��ȡAPN������Apn��ط���
 */
public class Apn {
	private static final Uri APN_TABLE_URI = Uri
			.parse("content://telephony/carriers");
	private static final Uri PREFERRED_APN_URI = Uri
			.parse("content://telephony/carriers/preferapn");

	
	private Context _c;
	
	public Apn(Context c)
	{
		_c=c;
	}
	
	/**
	 * ��ĳ��APN
	 * 
	 * @param apnnode
	 */
	public Boolean OpenApn(ApnNode apnnode) {
		if(apnnode==null)
			 return false;
		ContentValues cv = new ContentValues();
		cv.put("apn", ApnMatchTools.MatchApn(apnnode.getApn()));
		cv.put("type", ApnMatchTools.MatchApn(apnnode.getType()));
		_c.getContentResolver().update(APN_TABLE_URI, cv, "_id=?",
				new String[] { apnnode.getId() });
		return true;
	}

	/**
	 * �ر�ĳ��APN
	 * 
	 * @param apnnode
	 */
	public void CloseApn(ApnNode apnnode) {
		ContentValues cv = new ContentValues();
		cv.put("apn", ApnMatchTools.MatchApn(apnnode.getApn()) + "mdev");
		cv.put("type", ApnMatchTools.MatchApn(apnnode.getType()) + "mdev");
		_c.getContentResolver().update(APN_TABLE_URI, cv, "_id=?",
				new String[] { apnnode.getId() });
	}

	/**
	 * ������APN
	 */
	public void OpenAllAPN() {
		List<ApnNode> list = GetApnNodeList();
		for (ApnNode apn : list) {
			ContentValues cv = new ContentValues();
			cv.put("apn", ApnMatchTools.MatchApn(apn.getApn()));
			cv.put("type", ApnMatchTools.MatchApn(apn.getType()));
			_c.getContentResolver().update(APN_TABLE_URI, cv, "_id=?",
					new String[] { apn.getId() });

		}
	}

	/**
	 * �ر�����APN
	 */
	public void CloseAllAPN() {
		List<ApnNode> list = GetApnNodeList();
		for (ApnNode apn : list) {
			ContentValues cv = new ContentValues();
			cv.put("apn", ApnMatchTools.MatchApn(apn.getApn()) + "mdev");
			cv.put("type", ApnMatchTools.MatchApn(apn.getType()) + "mdev");
			_c.getContentResolver().update(APN_TABLE_URI, cv, "_id=?",
					new String[] { apn.getId() });

		}
	}
	
	/**
	 * �ж�����l��
	 * @param bnet ������l������mobileʱ��ʱ��Ҫ��Ϊ��net����
	 * @return �Ѿ�l���򷵻�true,δl���򷵻�false
	 */
	public Boolean IsNetworkLink(Boolean bnet)
	{
		switch (GetNetWorkType()) {
		case ConnectivityManager.TYPE_WIFI:
			return true;
		case ConnectivityManager.TYPE_MOBILE:
			if(!bnet) return true;
			if(IsWap()) return false;
			return true;

		default:
			return false;
		}
	}
	
	/**
	 * ������l��
	 * @param bnet ������l������mobileʱ��ʱ��Ҫ��Ϊ��net����
	 * @return ���ز���ʧ�ܻ�ɹ�
	 */
	public Boolean OpenNetwork(Boolean bnet)
	{
		if(IsNetworkLink(bnet)) return true;		

		ApnNode sapn=GetFirstDefaultAPN();
		if(IsWapApn(sapn))
		{
			sapn=GetNetApnNode(sapn);
			if(sapn==null) return false;
			if(!SetDefaultApn(sapn)) return false;
		}

		return OpenApn(sapn);		
	}

	/**
	 * ��õ�ǰj������wifi or mobile
	 * 
	 * @return -1: ��l������; ConnectivityManager.TYPE_WIFI: wifi;
	 *         ConnectivityManager.TYPE_MOBILE:mobile���ж�����l��״̬Ϊʱmobile�������ж���net����wap����
	 */
	public int GetNetWorkType() {
		if (getConnectManager() != null) {
			NetworkInfo networkInfo = getConnectManager()
					.getActiveNetworkInfo();
			if (networkInfo != null)
				return networkInfo.getType();
			return -1;
		} else {
			return -1;
		}
	}

	/**
	 * �жϵ�ǰl���Ƿ���WAP
	 * 
	 * @return
	 */
	public boolean IsWap() {
		int net_type = GetNetWorkType();
		if (net_type == ConnectivityManager.TYPE_MOBILE) {
			{
				// ���NET Wap�ж�
				ApnNode apn = GetFirstDefaultAPN();
				if (apn == null)
					return false;
				if (apn.getApn() != null && !apn.getApn().equals("")) {
					if (apn.getApn().toLowerCase().indexOf("wap") != -1)
						return true;
				} else if (apn.getUser() != null && !apn.getUser().equals(""))
					if (apn.getUser().toLowerCase().indexOf("wap") != -1)
						return true;
			}
		} else if (net_type == ConnectivityManager.TYPE_WIFI) {
			return false;
		}
		return false;
	}

	/**
	 * �ж��Ƿ���wap��apn
	 * 
	 * @param apn
	 * @return
	 */
	public boolean IsWapApn(ApnNode apn) {
		if (apn == null)
			return false;
		if (apn.getApn() != null && !apn.getApn().equals("")) {
			if (apn.getApn().toLowerCase().indexOf("wap") != -1)
				return true;
		} else if (apn.getUser() != null && !apn.getUser().equals(""))
			if (apn.getUser().toLowerCase().indexOf("wap") != -1)
				return true;
		return false;
	}

	/**
	 * �ж��Ƿ���net��apn
	 * 
	 * @param apn
	 * @return
	 */
	public boolean IsNetApn(ApnNode apn) {
		if (apn == null)
			return false;
		if (apn.getApn() != null && !apn.getApn().equals("")) {
			if (apn.getApn().toLowerCase().indexOf("net") != -1)
				return true;
		} else if (apn.getUser() != null && !apn.getUser().equals(""))
			if (apn.getUser().toLowerCase().indexOf("net") != -1)
				return true;
		return false;
	}

	/**
	 * �жϵ�ǰl���Ƿ���NET
	 * 
	 * @return
	 */
	public boolean IsNet() {
		int net_type = GetNetWorkType();
		if (net_type == ConnectivityManager.TYPE_MOBILE) {
			{
				// ���NET Wap�ж�
				ApnNode apn = GetFirstDefaultAPN();
				if (apn == null)
					return false;
				if (apn.getApn() != null && !apn.getApn().equals("")) {
					if (apn.getApn().toLowerCase().indexOf("net") != -1)
						return true;
				} else if (apn.getUser() != null && !apn.getUser().equals(""))
					if (apn.getUser().toLowerCase().indexOf("net") != -1)
						return true;
			}
		} else if (net_type == ConnectivityManager.TYPE_WIFI) {
			return false;
		}
		return false;
	}

	/**
	 * ��ȡȱʡ��APN
	 * 
	 * @return
	 */
	public ApnNode GetFirstDefaultAPN() {
		ArrayList<ApnNode> list = GetDefaultAPN();
		if (list == null || list.size() == 0)
			return null;
		return list.get(0);
	}

	/**
	 * ��ȡ��Ӧ��net����apn�����ԭ4����wap���磬�򷵻�null
	 * 
	 * @param apn
	 * @return ��ȡ��Ӧ��net����apn�����ԭ4����wap���磬�򷵻�null
	 */
	public ApnNode GetNetApnNode(ApnNode apn) {
		if (IsNetApn(apn))
			return apn;
		if (IsWapApn(apn)) {
			ArrayList<ApnNode> apnlist = GetApnNodeList();
			for (ApnNode tmpapn : apnlist) {
				if (tmpapn.getNumeric().equals(apn.getNumeric())) {
					if (IsNetApn(tmpapn))
						return tmpapn;
				}
			}
		}
		return null;
	}

	/**
	 * ��ȡȱʡ��APN�б�
	 * 
	 * @return
	 */
	public ArrayList<ApnNode> GetDefaultAPN() {
		// Uri uri = Uri.parse("content://telephony/carriers/preferapn");
		ArrayList<ApnNode> list = new ArrayList<ApnNode>();
		Cursor mCursor = _c.getContentResolver().query(PREFERRED_APN_URI, null,
				null, null, null);
		while (mCursor != null && mCursor.moveToNext()) {
			ApnNode apnNode = new ApnNode();
			apnNode.setId(GetCursorString(mCursor,"_id"));
			apnNode.setName(GetCursorString(mCursor,"name"));
			apnNode.setApn(GetCursorString(mCursor,"apn"));
			apnNode.setProxy(GetCursorString(mCursor,"proxy"));
			apnNode.setPort(GetCursorString(mCursor,"port"));
			apnNode.setUser(GetCursorString(mCursor,"user"));
			apnNode.setServer(GetCursorString(mCursor,"server"));
			apnNode.setPassword(GetCursorString(mCursor,"password"));
			apnNode.setMmsc(GetCursorString(mCursor,"mmsc"));
			apnNode.setMmsproxy(GetCursorString(mCursor,"mmsproxy"));
			apnNode.setMmsport(GetCursorString(mCursor,"mmsport"));
			apnNode.setMcc(GetCursorString(mCursor,"mcc"));
			apnNode.setMnc(GetCursorString(mCursor,"mnc"));
			apnNode.setNumeric(GetCursorString(mCursor,"numeric"));
			apnNode.setType(GetCursorString(mCursor,"type"));
			apnNode.setCurrent(GetCursorString(mCursor,"current"));
			list.add(apnNode);
		}

		return list;
	}
	
	private String GetCursorString(Cursor cursor,String column)
	{
		int index=cursor.getColumnIndex(column);
		if(index<0)
			return null;
		return cursor.getString(index);
	}

	/**
	 * ����Ϊȱʡ��APN
	 * 
	 * @param apnId
	 * @return
	 */
	public boolean SetDefaultApn(ApnNode apn) {
		
		if(apn==null) return false;
		
		int apnId=Integer.parseInt(apn.getId());
		
		boolean res = false;
		ContentResolver resolver = _c.getContentResolver();
		ContentValues values = new ContentValues();
		values.put("apn_id", apnId);

		try {
			resolver.update(PREFERRED_APN_URI, values, null, null);
			Cursor c = resolver.query(PREFERRED_APN_URI, new String[] { "name",
					"apn" }, "_id=" + apnId, null, null);
			if (c != null) {
				res = true;
				c.close();
			}
		} catch (SQLException e) {

		}
		return res;
	}
	
	/**
	 * �ж�APN����(���Ǹ��ID�жϣ��������)
	 * 
	 * @param apnNode
	 * @return ApnNode һ�µ�ApnNode,����Ϊnull
	 */
	public ApnNode IsApnExisted(ApnNode apnNode) {

		ArrayList<ApnNode> list = GetApnNodeList();

		if (list == null || list.size() <= 0)
			return null;

		for (int i = 0; i < list.size(); i++) {
			if ((apnNode.getApn().equals(list.get(i).getApn())
					&& apnNode.getMcc().equals(list.get(i).getMnc())
					&& apnNode.getMnc().equals(list.get(i).getMnc()) && apnNode
					.getNumeric().equals(list.get(i).getNumeric()))
					&& (list.get(i).getType() == null
							|| "default".equals(list.get(i).getType()) || ""
							.equals(list.get(i).getType())))// ||
															// (apnNode.getApn().equals(apn)
			// && "".equals(proxy) &&
			// "".equals(port))
			{
				return list.get(i);
			}
		}
		return null;
	}

	/**
	 * �������l�ӹ���
	 * 
	 * @return
	 */
	private ConnectivityManager getConnectManager() {

		ConnectivityManager m_ConnectivityManager = (ConnectivityManager) _c.getSystemService(Context.CONNECTIVITY_SERVICE);

		return m_ConnectivityManager;
	}

	/**
	 * ��ȡ���е�Apn��Ϣ
	 * @return Apn��Ϣ�б�
	 */
	public ArrayList<ApnNode> GetApnNodeList() {
		ArrayList<ApnNode> list = new ArrayList<ApnNode>();
		Cursor mCursor = _c.getContentResolver().query(APN_TABLE_URI, null, null,
				null, null);
		while (mCursor != null && mCursor.moveToNext()) {
			ApnNode apnNode = new ApnNode();
			apnNode.setId(GetCursorString(mCursor,"_id"));
			apnNode.setName(GetCursorString(mCursor,"name"));
			apnNode.setApn(GetCursorString(mCursor,"apn"));
			apnNode.setProxy(GetCursorString(mCursor,"proxy"));
			apnNode.setPort(GetCursorString(mCursor,"port"));
			apnNode.setUser(GetCursorString(mCursor,"user"));
			apnNode.setServer(GetCursorString(mCursor,"server"));
			apnNode.setPassword(GetCursorString(mCursor,"password"));
			apnNode.setMmsc(GetCursorString(mCursor,"mmsc"));
			apnNode.setMmsproxy(GetCursorString(mCursor,"mmsproxy"));
			apnNode.setMmsport(GetCursorString(mCursor,"mmsport"));
			apnNode.setMcc(GetCursorString(mCursor,"mcc"));
			apnNode.setMnc(GetCursorString(mCursor,"mnc"));
			apnNode.setNumeric(GetCursorString(mCursor,"numeric"));
			apnNode.setType(GetCursorString(mCursor,"type"));
			apnNode.setCurrent(GetCursorString(mCursor,"current"));
			list.add(apnNode);
		}

		return list;
	}
	
}
